<template>
  <div class="content-card">
    <div class="page-header">
      <h2>商品列表</h2>
      <el-button type="primary" @click="handleAdd">添加商品</el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="searchForm.name" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="searchForm.categoryId" placeholder="请选择商品分类">
          <el-option label="全部" value="" />
          <el-option label="电子产品" value="1" />
          <el-option label="服装鞋帽" value="2" />
          <el-option label="家居用品" value="3" />
          <el-option label="美妆护肤" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品品牌" prop="brandId">
        <el-select v-model="searchForm.brandId" placeholder="请选择商品品牌">
          <el-option label="全部" value="" />
          <el-option label="品牌A" value="1" />
          <el-option label="品牌B" value="2" />
          <el-option label="品牌C" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择上架状态">
          <el-option label="全部" value="" />
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 商品表格 -->
    <el-table 
      v-loading="loading" 
      :data="productList" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="商品ID" width="80" />
      <el-table-column prop="name" label="商品名称" min-width="180" />
      <el-table-column prop="categoryName" label="商品分类" width="120" />
      <el-table-column prop="brandName" label="商品品牌" width="120" />
      <el-table-column prop="price" label="价格" width="100" formatter="formatPrice" />
      <el-table-column prop="stock" label="库存" width="80" />
      <el-table-column prop="sales" label="销量" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button 
            :type="scope.row.status === 1 ? 'warning' : 'success'" 
            size="small" 
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <div class="pagination-info">
        共 {{ total }} 条记录，每页显示 {{ pageSize }} 条
      </div>
      <el-pagination 
        v-model:current-page="currentPage" 
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedProducts.length > 0">
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" @click="handleBatchPublish">批量上架</el-button>
      <el-button type="warning" @click="handleBatchUnpublish">批量下架</el-button>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productApi } from '../../api/product.js'

export default {
  name: 'ProductList',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const productList = ref([])
    const selectedProducts = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      categoryId: '',
      brandId: '',
      status: ''
    })
    
    // 格式化价格
    const formatPrice = (row, column, cellValue) => {
      return `¥${cellValue.toFixed(2)}`
    }
    
    // 获取商品列表
    const getProductList = async () => {
      loading.value = true
      try {
        const params = {
          ...searchForm,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 模拟API请求，使用mock数据
        setTimeout(() => {
          productList.value = generateMockData()
          total.value = 100
          loading.value = false
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // const response = await productApi.getProductList(params)
        // productList.value = response.data.list
        // total.value = response.data.total
        // loading.value = false
      } catch (error) {
        console.error('获取商品列表失败:', error)
        ElMessage.error('获取商品列表失败')
        loading.value = false
      }
    }
    
    // 生成模拟数据
    const generateMockData = () => {
      const categories = ['电子产品', '服装鞋帽', '家居用品', '美妆护肤']
      const brands = ['品牌A', '品牌B', '品牌C', '品牌D']
      const products = []
      
      for (let i = 0; i < pageSize.value; i++) {
        const index = (currentPage.value - 1) * pageSize.value + i + 1
        products.push({
          id: index,
          name: `商品${index}`,
          categoryName: categories[Math.floor(Math.random() * categories.length)],
          brandName: brands[Math.floor(Math.random() * brands.length)],
          price: Math.floor(Math.random() * 1000) + 100,
          stock: Math.floor(Math.random() * 1000),
          sales: Math.floor(Math.random() * 10000),
          status: Math.random() > 0.3 ? 1 : 0,
          createTime: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)).toLocaleString()
        })
      }
      
      return products
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getProductList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      getProductList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      getProductList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      currentPage.value = current
      getProductList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedProducts.value = selection
    }
    
    // 处理添加商品
    const handleAdd = () => {
      router.push('/product/add')
    }
    
    // 处理编辑商品
    const handleEdit = (product) => {
      router.push(`/product/edit/${product.id}`)
    }
    
    // 处理删除商品
    const handleDelete = (id) => {
      ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟删除请求
          setTimeout(() => {
            ElMessage.success('删除成功')
            getProductList()
          }, 500)
          
          // 实际API调用代码（目前注释掉）
          // await productApi.deleteProduct(id)
          // ElMessage.success('删除成功')
          // getProductList()
        } catch (error) {
          console.error('删除商品失败:', error)
          ElMessage.error('删除商品失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 处理状态变更
    const handleStatusChange = async (product) => {
      try {
        const newStatus = product.status === 1 ? 0 : 1
        // 模拟状态变更请求
        setTimeout(() => {
          product.status = newStatus
          ElMessage.success(`${newStatus === 1 ? '上架' : '下架'}成功`)
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // await productApi.changeProductStatus(product.id, newStatus)
        // product.status = newStatus
        // ElMessage.success(`${newStatus === 1 ? '上架' : '下架'}成功`)
      } catch (error) {
        console.error('状态变更失败:', error)
        ElMessage.error('状态变更失败')
      }
    }
    
    // 处理批量删除
    const handleBatchDelete = () => {
      ElMessageBox.confirm(`确定要删除选中的 ${selectedProducts.value.length} 个商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = selectedProducts.value.map(product => product.id)
          // 模拟批量删除请求
          setTimeout(() => {
            ElMessage.success('批量删除成功')
            selectedProducts.value = []
            getProductList()
          }, 500)
          
          // 实际API调用代码（目前注释掉）
          // await productApi.batchDeleteProducts(ids)
          // ElMessage.success('批量删除成功')
          // selectedProducts.value = []
          // getProductList()
        } catch (error) {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 处理批量上架
    const handleBatchPublish = async () => {
      try {
        const ids = selectedProducts.value.map(product => product.id)
        // 模拟批量上架请求
        setTimeout(() => {
          ElMessage.success('批量上架成功')
          selectedProducts.value = []
          getProductList()
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // await productApi.batchPublishProducts(ids)
        // ElMessage.success('批量上架成功')
        // selectedProducts.value = []
        // getProductList()
      } catch (error) {
        console.error('批量上架失败:', error)
        ElMessage.error('批量上架失败')
      }
    }
    
    // 处理批量下架
    const handleBatchUnpublish = async () => {
      try {
        const ids = selectedProducts.value.map(product => product.id)
        // 模拟批量下架请求
        setTimeout(() => {
          ElMessage.success('批量下架成功')
          selectedProducts.value = []
          getProductList()
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // await productApi.batchUnpublishProducts(ids)
        // ElMessage.success('批量下架成功')
        // selectedProducts.value = []
        // getProductList()
      } catch (error) {
        console.error('批量下架失败:', error)
        ElMessage.error('批量下架失败')
      }
    }
    
    // 初始化数据
    onMounted(() => {
      getProductList()
    })
    
    return {
      loading,
      productList,
      selectedProducts,
      total,
      currentPage,
      pageSize,
      searchForm,
      formatPrice,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleStatusChange,
      handleBatchDelete,
      handleBatchPublish,
      handleBatchUnpublish
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  
  .el-form-item {
    margin-right: 20px;
  }
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  
  .pagination-info {
    color: var(--text-secondary);
    font-size: 14px;
  }
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  
  .el-button {
    margin-right: 10px;
  }
}
</style>